using Domain.Entities;
using Domain.Permissions;
using Domain.Mail;
using Domain.Services;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using UserInterface.Misc;
using UserInterface.MML;
using System.Collections.Generic;

namespace UserInterface
{
    public partial class ViewTopic : BoardPageBase
    {
        private Topic topic;
        private ForumPermissionManager forumPermissionManager;
        private string currentTemplate;

        protected void Page_Load(object sender, EventArgs e)
        {
            int topicId = int.Parse(Request.QueryString["topicId"]);

            topic = TopicService.GetById(topicId);
            forumPermissionManager = PermissionManager.CreateForumPermissionManager(topic.Forum);
            currentTemplate = SessionManager.CurrentSession.CurrentTemplate;

            if (!forumPermissionManager.Read)
            {
                DieMessage(DieMessageType.InsufficientPermissions, "InsufficientPermissions");
            }

            if (Request.QueryString["lock"] != null && forumPermissionManager.Moderate)
            {
                if (topic.Locked)
                {
                    TopicService.UnlockTopic(topic);
                }
                else
                {
                    TopicService.LockTopic(topic);
                }
            }

            string pageTitle = (string)GetLocalResourceObject("Title");

            MasterPage.TitleGenerator.PageTitle = pageTitle;
            MasterPage.TitleGenerator.ItemName = topic.Subject;
            MasterPage.HeaderText = topic.Subject;
            MasterPage.AddPathItem(topic.Forum.Name, "ViewForum.aspx?forumId=" + topic.Forum.Id);
            MasterPage.AddPathItem(topic.Subject, "ViewTopic.aspx?topicId=" + topic.Id);

            ShowMessages();
        }

        private void ShowMessages()
        {
            if (forumPermissionManager.Reply && !topic.Locked)
            {
                MasterPage.AddNavigationItem("Templates/" + currentTemplate + "/Images/Icons/add-message.gif", "AddMessage.aspx?topicId=" + topic.Id, "");
            }
            if (forumPermissionManager.Moderate)
            {
                MasterPage.AddNavigationItem("Templates/" + currentTemplate + "/Images/Icons/move-topic.gif", "MoveTopic.aspx?topicId=" + topic.Id, "");

                if (!topic.Locked)
                {
                    MasterPage.AddNavigationItem("Templates/" + currentTemplate + "/Images/Icons/lock-topic.gif", "ViewTopic.aspx?topicId=" + topic.Id + "&lock=1", "", "return confirm('Are you sure you want to lock this topic?');");
                }
                else
                {
                    MasterPage.AddNavigationItem("Templates/" + currentTemplate + "/Images/Icons/unlock-topic.gif", "ViewTopic.aspx?topicId=" + topic.Id + "&lock=0", "", "return confirm('Are you sure you want to unlock this topic?');");
                }
            }
            if (!CurrentSession.IsGuest && (!topic.Locked || forumPermissionManager.Moderate) && (forumPermissionManager.Moderate || (forumPermissionManager.EditOwn && topic.StartMessage.Poster.Id == CurrentSession.UserId)))
            {
                MasterPage.AddNavigationItem("Templates/" + currentTemplate + "/Images/Icons/edit-topic.gif", "EditTopic.aspx?topicId=" + topic.Id, "");
            }

            bool isModerator = forumPermissionManager.Moderate;
            User user = CurrentSession.User;
            int messagesPerPage = PagingTools.GetMessagesPerPage(user);
            int messageCount = MessageService.GetMessageCountForTopic(topic, isModerator);
            int pageCount = PagingTools.GetPageCount(messageCount, messagesPerPage);
            int currentPage = PagingTools.GetPage(Request.QueryString["page"], pageCount);

            string messageIdStr = (string)Request.QueryString["messageId"];
            if (messageIdStr != null)
            {
                int messageId;
                if (int.TryParse(messageIdStr, out messageId))
                {
                    Message message = MessageService.GetById(messageId);
                    if (message != null && message.Topic.Id == topic.Id)
                    {
                        int messageOffset = MessageService.GetOffsetOfMessage(message, isModerator);
                        currentPage = PagingTools.GetPageAtOffset(messageOffset, messagesPerPage);
                    }
                }
            }
            
            string urlBase = "ViewTopic.aspx?topicId=" + topic.Id;
            PagingTools.InitPagers(
                pageCount, currentPage, urlBase,
                TopPager, BottomPager
            );

            IList<Message> messages = MessageService.GetMessagesPaged(topic, isModerator, currentPage, messagesPerPage);

            MessageRepeater.DataSource = messages;
            MessageRepeater.DataBind();
        }

        protected void QuickReplyButton_Click(object sender, EventArgs e)
        {
            User poster = CurrentSession.User;
            string text = QuickReplyText.Text;
            QuickReplyText.Text = String.Empty;
            Message message = MessageService.NewMessage(topic, poster, text, false);
            SendEmailNotifications(message);

            Response.Redirect("ViewTopic.aspx?topicId=" + topic.Id + "&messageId=" + message.Id + "#message_" + message.Id);
        }

        protected void AddBookmarkImageButton_Click(object sender, EventArgs e)
        {
            if (BookmarkService.GetByTopicAndUser(topic, CurrentSession.User) == null)
            {
                BookmarkService.NewBookmark(topic, CurrentSession.User, true);
            }
            else
            {
                MasterPage.Messages.AddExclamation("You have already bookmarked this topic.");
            }
        }

        protected void MessageRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Message message = e.Item.DataItem as Message;
            }
        }

        private void SendEmailNotifications(Message message)
        {
            foreach (Bookmark bookmark in topic.Bookmarks)
            {
                MailParser mailParser = new MailParser(Server.MapPath("~/Emails/TopicEmailNotification.xml"));
                mailParser.AddSubjectTag("Subject", topic.Subject);
                mailParser.AddBodyTag("Username", bookmark.User.Username);
                mailParser.AddBodyTag("PosterUsername", message.Poster.Username);
                mailParser.AddBodyTag("MessageUrl", "http://" + Request.ServerVariables["HTTP_HOST"] + "/ViewTopic.aspx?topicId=" + topic.Id + "&messageId=" + message.Id + "#message_" + message.Id);

                MailSender mailSender = new MailSender(mailParser);
                mailSender.AddRecipient(bookmark.User.Email);
                mailSender.Send();
            }
        }
    }
}
